﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Configuration;

namespace DMS.PdfViewer
{
    [ToolboxItemAttribute(false)]
    public class PdfViewer : WebPart
    {
        private string pdfDocumentPath = string.Empty;
        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);
        }

        public PdfViewer()
        {
            this.PreRender += new EventHandler(PdfViewer_PreRender);
            string id = HttpContext.Current.Request["ID"];
            int listId;
            bool isValidId = Int32.TryParse(id, out listId);
            if (isValidId)
            {
                pdfDocumentPath = GetPDFDocumentName(listId);
            }
        }

        void PdfViewer_PreRender(object sender, EventArgs e)
        {

        }

        private string GetPDFDocumentName(int listId)
        {
            string pdfFullPath = string.Empty;
            //string siteUrl = ConfigurationManager.AppSettings["SiteUrl"]; 
            //string webUrl = ConfigurationManager.AppSettings["WebUrl"];
            //string docStoreName = ConfigurationManager.AppSettings["DocStore"];
            string siteUrl = "http://turnersintranet/sites/dms";
            string webRelativeUrl = "/";
            string docStoreName = "Document Store";
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb(webRelativeUrl))
                {
                    SPList documentStore = web.Lists[docStoreName];
                    SPListItem document = documentStore.GetItemById(listId);
                    string webUrl = web.Url;
                    if (document != null)
                    {
                        string pdfName = document["Name"].ToString();
                        pdfFullPath = String.Format("{0}/{1}/{2}", webUrl,docStoreName, pdfName);
                    }
                }
            }
            return pdfFullPath;
        }
        protected override void CreateChildControls()
        {
            LiteralControl pdfHolder = new LiteralControl();
            if (string.IsNullOrEmpty(pdfDocumentPath))
            {
                pdfHolder.Text = "Invalid Parameter: No PDF document loaded";
            }
            else
            {
                pdfHolder.Text = "Hello world" + pdfDocumentPath;
            }
            this.Controls.Add(pdfHolder);
        }
    }
}
